import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/camera_models.dart';
import '../implementations/flutter_camera_implementation.dart';
import '../implementations/native_implementation.dart';
import '../utils/permission_manager.dart';

/// 多摄像头管理器
///
/// 这是插件的核心类，负责管理多种摄像头实现方案，
/// 提供自动降级和手动切换功能，确保最大的设备兼容性。
class MultiCameraManager {
  static MultiCameraManager? _instance;
  static MultiCameraManager get instance =>
      _instance ??= MultiCameraManager._();

  MultiCameraManager._();

  // 状态管理
  CameraStatus _status = CameraStatus.uninitialized;
  CameraImplementationType? _currentImplementation;
  CameraConfig? _config;
  CameraImplementationPriority _priority = const CameraImplementationPriority();

  // 可用的实现方案
  final List<CameraImplementationType> _availableImplementations = [];

  // 事件流控制器
  StreamController<CameraEvent> _eventController =
      StreamController<CameraEvent>.broadcast();
  StreamController<CameraStatus> _statusController =
      StreamController<CameraStatus>.broadcast();
  StreamController<CameraError> _errorController =
      StreamController<CameraError>.broadcast();

  // 重试计数
  int _retryCount = 0;

  // 自动初始化标志
  bool _autoInitializationEnabled = false;
  bool _isAutoInitializing = false;
  BuildContext? _autoInitContext;

  // 检测状态
  bool _isDetecting = false;

  // Session控制状态
  bool _isSessionPaused = false;
  String? _lastCapturedImagePath; // 最后拍摄的照片路径，用于暂停时显示

  /// 事件流
  Stream<CameraEvent> get eventStream => _eventController.stream;

  /// 状态流
  Stream<CameraStatus> get statusStream => _statusController.stream;

  /// 错误流
  Stream<CameraError> get errorStream => _errorController.stream;

  /// 当前状态
  CameraStatus get status => _status;

  /// 当前实现类型
  CameraImplementationType? get currentImplementation => _currentImplementation;

  /// 可用的实现方案
  List<CameraImplementationType> get availableImplementations =>
      List.unmodifiable(_availableImplementations);

  /// 是否启用了自动初始化
  bool get isAutoInitializationEnabled => _autoInitializationEnabled;

  /// session是否已暂停
  bool get isSessionPaused => _isSessionPaused;

  /// 获取最后拍摄的照片路径（用于暂停时显示）
  String? get lastCapturedImagePath => _lastCapturedImagePath;

  /// 初始化摄像头管理器
  Future<void> initialize({
    required CameraConfig config,
    CameraImplementationPriority? priority,
    CameraImplementationType? preferredImplementation,
    BuildContext? context,
  }) async {
    try {
      _updateStatus(CameraStatus.initializing);

      _config = config;
      if (priority != null) {
        _priority = priority;
      }

      // 检查相机权限
      final permissionResult = await PermissionManager.handleCameraPermission(
        context,
        showDialog: context != null,
      );

      debugPrint('🔐 权限检查结果: $permissionResult');

      if (!permissionResult.isGranted) {
        // 权限被拒绝，抛出相应的错误
        if (permissionResult.needsManualSettings) {
          throw CameraError(
            code: 'PERMISSION_PERMANENTLY_DENIED',
            message: '相机权限被拒绝，请前往系统设置手动开启相机权限',
          );
        } else if (permissionResult.userDenied) {
          throw CameraError(
            code: 'PERMISSION_DENIED',
            message: '用户拒绝了相机权限',
          );
        } else if (permissionResult.hasError) {
          throw CameraError(
            code: 'PERMISSION_ERROR',
            message: '权限检查失败: ${permissionResult.errorMessage}',
          );
        } else {
          throw CameraError(
            code: 'PERMISSION_UNKNOWN',
            message: '未知的权限错误',
          );
        }
      }

      // 检测可用的实现方案
      await _detectAvailableImplementations();

      if (_availableImplementations.isEmpty) {
        throw CameraError(
          code: 'NO_IMPLEMENTATIONS',
          message: '未找到可用的摄像头实现方案',
        );
      }

      // 选择实现方案
      CameraImplementationType? implementationType;
      if (preferredImplementation != null &&
          _availableImplementations.contains(preferredImplementation)) {
        implementationType = preferredImplementation;
      } else {
        implementationType = await _selectBestImplementation();
      }

      if (implementationType == null) {
        throw CameraError(
          code: 'NO_SUITABLE_IMPLEMENTATION',
          message: '未找到合适的摄像头实现方案',
        );
      }

      // 初始化选定的实现方案
      await _initializeImplementation(implementationType);

      _updateStatus(CameraStatus.initialized);

      // 保存用户偏好
      await _saveUserPreference(implementationType);
    } catch (e) {
      debugPrint('❌ MultiCameraManager: 初始化失败，尝试智能错误处理: $e');

      final cameraError = e is CameraError
          ? e
          : CameraError(
              code: 'INITIALIZATION_FAILED',
              message: '摄像头初始化失败: ${e.toString()}',
            );

      // 使用智能错误处理
      if (_priority.enableSmartErrorHandling) {
        final severity = ErrorClassifier.classifyError(
            cameraError.code, cameraError.message);

        switch (severity) {
          case ErrorSeverity.severe:
            // 严重错误，直接抛出，不进行降级
            debugPrint('❌ 严重错误，需要用户干预: ${cameraError.message}');
            _handleError(cameraError);
            return;

          case ErrorSeverity.minor:
            // 轻微错误，短暂延迟后重试当前实现
            if (_retryCount < _priority.maxRetryCount) {
              _retryCount++;
              debugPrint(
                  '🔄 轻微错误，延迟后重试 ($_retryCount/$_priority.maxRetryCount)');
              await Future.delayed(
                  Duration(milliseconds: _priority.retryDelayMs));
              return await initialize(config: _config!, priority: _priority);
            }
            break;

          case ErrorSeverity.moderate:
            // 中等错误，尝试降级
            break;
        }
      }

      // 尝试自动降级到其他实现方案
      if (_priority.enableAutoFallback &&
          _retryCount < _priority.maxRetryCount) {
        try {
          await _tryInitializationFallback('初始化失败', e);
          // 如果降级成功，不抛出错误
          return;
        } catch (fallbackError) {
          // 如果降级也失败，记录原始错误和降级错误
          debugPrint('❌ MultiCameraManager: 自动降级也失败: $fallbackError');
        }
      }

      _handleError(cameraError);
    }
  }

  /// 启用自动初始化
  ///
  /// [config] 摄像头配置
  /// [priority] 实现方案优先级配置
  /// [preferredImplementation] 首选实现方案
  /// [context] BuildContext，用于显示权限对话框
  Future<void> enableAutoInitialization({
    required CameraConfig config,
    CameraImplementationPriority? priority,
    CameraImplementationType? preferredImplementation,
    BuildContext? context,
  }) async {
    _config = config;
    if (priority != null) {
      _priority = priority;
    }
    _autoInitializationEnabled = true;
    _autoInitContext = context;

    // 检测可用的实现方案
    await _detectAvailableImplementations();

    // 发送状态变化事件，通知UI更新
    _eventController.add(CameraStatusChangedEvent(_status));

    debugPrint(
        '🔄 MultiCameraManager: 自动初始化已启用，可用实现: ${_availableImplementations.map((impl) => impl.name).join(', ')}');

    // 立即触发自动初始化
    await _autoInitialize();
  }

  /// 禁用自动初始化
  void disableAutoInitialization() {
    _autoInitializationEnabled = false;
    debugPrint('🔄 MultiCameraManager: 自动初始化已禁用');
  }

  /// 自动初始化摄像头
  ///
  /// 这个方法会在需要时自动调用，不需要手动调用
  Future<void> _autoInitialize() async {
    if (!_autoInitializationEnabled ||
        _isAutoInitializing ||
        _status == CameraStatus.initialized ||
        _status == CameraStatus.initializing) {
      return;
    }

    if (_config == null) {
      _handleError(CameraError(
        code: 'NO_CONFIG_FOR_AUTO_INIT',
        message: '自动初始化失败：未设置摄像头配置',
      ));
      return;
    }

    debugPrint('🔄 MultiCameraManager: 开始自动初始化...');
    _isAutoInitializing = true;

    // 发送自动初始化开始事件
    _eventController.add(AutoInitializationStartedEvent(_config!));

    try {
      await initialize(
        config: _config!,
        priority: _priority,
        context: _autoInitContext,
      );
      debugPrint('✅ MultiCameraManager: 自动初始化成功');

      // 发送自动初始化成功事件
      _eventController.add(AutoInitializationCompletedEvent(
        _currentImplementation!,
        true,
      ));
    } catch (e) {
      debugPrint('❌ MultiCameraManager: 自动初始化失败: $e');
      final errorMessage = e.toString();

      // 发送自动初始化失败事件
      _eventController.add(AutoInitializationCompletedEvent(
        _currentImplementation ?? CameraImplementationType.native,
        false,
        errorMessage,
      ));

      _handleError(CameraError(
        code: 'AUTO_INITIALIZATION_FAILED',
        message: '自动初始化失败: $errorMessage',
      ));
    } finally {
      _isAutoInitializing = false;
    }
  }

  /// 创建摄像头预览Widget
  Widget buildPreview({
    required CameraPreviewConfig previewConfig,
    VoidCallback? onCameraReady,
    Function(CameraError)? onError,
  }) {
    // 如果未初始化且启用了自动初始化，则触发自动初始化
    if (_status == CameraStatus.uninitialized && _autoInitializationEnabled) {
      // 异步调用自动初始化，不阻塞Widget构建
      Future.microtask(() => _autoInitialize());

      return Container(
        color: Colors.black,
        child: const Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(color: Colors.white),
              SizedBox(height: 16),
              Text(
                '正在自动初始化摄像头...',
                style: TextStyle(color: Colors.white),
              ),
            ],
          ),
        ),
      );
    }

    if (_status != CameraStatus.initialized &&
            _status != CameraStatus.sessionPaused ||
        _currentImplementation == null) {
      return Container(
        color: Colors.black,
        child: const Center(
          child: Text(
            '摄像头未初始化',
            style: TextStyle(color: Colors.white),
          ),
        ),
      );
    }

    // 构建基础预览（始终显示实时预览）
    Widget basePreview;
    switch (_currentImplementation!) {
      case CameraImplementationType.flutterCamera:
        basePreview = FlutterCameraImplementation.buildPreview(
          previewConfig: previewConfig,
          onCameraReady: onCameraReady,
          onError: (error) {
            _handlePreviewError(error, onError);
          },
        );
        break;

      case CameraImplementationType.native:
        basePreview = NativeImplementation.buildPreview(
          previewConfig: previewConfig,
          onCameraReady: onCameraReady,
          onError: (error) {
            _handlePreviewError(error, onError);
          },
        );
        break;
    }

    // 直接返回基础预览，无论状态如何
    return basePreview;
  }

  /// 拍照
  Future<CaptureResult> takePicture() async {
    // 如果未初始化且启用了自动初始化，则自动初始化
    if (_status == CameraStatus.uninitialized && _autoInitializationEnabled) {
      await _autoInitialize();
    }

    if (_status != CameraStatus.initialized || _currentImplementation == null) {
      throw CameraError(
        code: 'NOT_INITIALIZED',
        message: '摄像头未初始化',
      );
    }

    try {
      // 不再更改状态为takingPicture，保持预览界面不变

      CaptureResult result;
      switch (_currentImplementation!) {
        case CameraImplementationType.flutterCamera:
          result = await FlutterCameraImplementation.takePicture();
          break;

        case CameraImplementationType.native:
          result = await NativeImplementation.takePicture();
          break;
      }

      // 保持原状态不变

      // 保存最后拍摄的照片路径
      _lastCapturedImagePath = result.imagePath;

      // 发送拍照完成事件
      _eventController
          .add(CameraCaptureCompletedEvent(result, _currentImplementation!));

      return result;
    } catch (e) {
      // 失败时也保持原状态不变

      final cameraError = e is CameraError
          ? e
          : CameraError(
              code: 'CAPTURE_FAILED',
              message: '拍照失败: ${e.toString()}',
            );

      // 使用智能错误处理
      if (_priority.enableSmartErrorHandling) {
        final severity = ErrorClassifier.classifyError(
            cameraError.code, cameraError.message);

        switch (severity) {
          case ErrorSeverity.severe:
            // 严重错误，直接抛出
            debugPrint('❌ 拍照严重错误，需要用户干预: ${cameraError.message}');
            throw cameraError;

          case ErrorSeverity.minor:
            // 轻微错误，延迟后重试
            if (_retryCount < _priority.maxRetryCount) {
              _retryCount++;
              debugPrint(
                  '🔄 拍照轻微错误，延迟后重试 ($_retryCount/${_priority.maxRetryCount})');
              await Future.delayed(
                  Duration(milliseconds: _priority.retryDelayMs));
              return await takePicture();
            }
            break;

          case ErrorSeverity.moderate:
            // 中等错误，尝试降级
            break;
        }
      }

      // 如果拍照失败且启用了自动降级，尝试切换实现方案
      if (_priority.enableAutoFallback &&
          _retryCount < _priority.maxRetryCount) {
        try {
          await _tryFallbackImplementation('拍照失败');
          // 降级成功后重试，但不使用递归，而是直接调用
          _retryCount = 0; // 重置重试计数，因为已经切换了实现
          return await takePicture();
        } catch (fallbackError) {
          debugPrint('❌ 拍照降级失败: $fallbackError');
        }
      }

      throw cameraError;
    }
  }

  /// 切换摄像头方向
  Future<void> switchCamera(CameraLensDirection direction) async {
    // 如果未初始化且启用了自动初始化，则自动初始化
    if (_status == CameraStatus.uninitialized && _autoInitializationEnabled) {
      await _autoInitialize();
    }

    if (_status != CameraStatus.initialized || _currentImplementation == null) {
      throw CameraError(
        code: 'NOT_INITIALIZED',
        message: '摄像头未初始化',
      );
    }

    try {
      final oldDirection = _getCurrentDirection();

      switch (_currentImplementation!) {
        case CameraImplementationType.flutterCamera:
          await FlutterCameraImplementation.switchCamera(direction);
          break;

        case CameraImplementationType.native:
          await NativeImplementation.switchCamera(direction);
          break;
      }

      // 发送摄像头方向切换事件
      _eventController
          .add(CameraDirectionSwitchedEvent(oldDirection, direction));
    } catch (e) {
      if (e is CameraError) {
        rethrow;
      } else {
        throw CameraError(
          code: 'SWITCH_CAMERA_FAILED',
          message: '切换摄像头失败: ${e.toString()}',
        );
      }
    }
  }

  /// 设置闪光灯模式
  Future<void> setFlashMode(FlashMode mode) async {
    // 如果未初始化且启用了自动初始化，则自动初始化
    if (_status == CameraStatus.uninitialized && _autoInitializationEnabled) {
      await _autoInitialize();
    }

    if (_status != CameraStatus.initialized || _currentImplementation == null) {
      throw CameraError(
        code: 'NOT_INITIALIZED',
        message: '摄像头未初始化',
      );
    }

    try {
      final oldMode = _getCurrentFlashMode();

      switch (_currentImplementation!) {
        case CameraImplementationType.flutterCamera:
          await FlutterCameraImplementation.setFlashMode(mode);
          break;

        case CameraImplementationType.native:
          await NativeImplementation.setFlashMode(mode);
          break;
      }

      // 发送闪光灯模式变化事件
      _eventController.add(FlashModeChangedEvent(oldMode, mode));
    } catch (e) {
      if (e is CameraError) {
        rethrow;
      } else {
        throw CameraError(
          code: 'SET_FLASH_MODE_FAILED',
          message: '设置闪光灯模式失败: ${e.toString()}',
        );
      }
    }
  }

  /// 暂停摄像头session（冻结预览）
  Future<void> pauseSession() async {
    if (_status != CameraStatus.initialized || _currentImplementation == null) {
      throw CameraError(
        code: 'NOT_INITIALIZED',
        message: '摄像头未初始化',
      );
    }

    if (_isSessionPaused) {
      return; // 已经暂停了
    }

    try {
      // 调用底层实现的暂停方法，真正暂停相机预览
      switch (_currentImplementation!) {
        case CameraImplementationType.flutterCamera:
          await FlutterCameraImplementation.pauseSession();
          break;
        case CameraImplementationType.native:
          await NativeImplementation.pauseSession();
          break;
      }

      _isSessionPaused = true;
      _updateStatus(CameraStatus.sessionPaused);

      // 发送session暂停事件
      _eventController.add(CameraSessionPausedEvent(
        _currentImplementation!,
        '用户手动暂停',
      ));

      debugPrint('📱 MultiCameraManager: session已暂停，相机预览已冻结');
    } catch (e) {
      throw CameraError(
        code: 'PAUSE_SESSION_FAILED',
        message: '暂停session失败: ${e.toString()}',
      );
    }
  }

  /// 恢复摄像头session（恢复实时预览）
  Future<void> resumeSession() async {
    if (_status != CameraStatus.sessionPaused ||
        _currentImplementation == null) {
      throw CameraError(
        code: 'SESSION_NOT_PAUSED',
        message: 'Session未暂停或摄像头未初始化',
      );
    }

    try {
      // 调用底层实现的恢复方法，重新开始相机预览
      switch (_currentImplementation!) {
        case CameraImplementationType.flutterCamera:
          await FlutterCameraImplementation.resumeSession();
          break;
        case CameraImplementationType.native:
          await NativeImplementation.resumeSession();
          break;
      }

      _isSessionPaused = false;
      _updateStatus(CameraStatus.initialized);

      // 发送session恢复事件
      _eventController.add(CameraSessionResumedEvent(_currentImplementation!));

      debugPrint('📱 MultiCameraManager: session已恢复，相机预览已重新开始');
    } catch (e) {
      throw CameraError(
        code: 'RESUME_SESSION_FAILED',
        message: '恢复session失败: ${e.toString()}',
      );
    }
  }

  /// 手动切换实现方案
  Future<void> switchImplementation(
      CameraImplementationType implementationType) async {
    debugPrint('🔄 MultiCameraManager: 开始切换实现方案');
    debugPrint('🔄 目标实现: ${implementationType.name}');
    debugPrint('🔄 当前实现: ${_currentImplementation?.name ?? 'null'}');
    debugPrint(
        '🔄 可用实现: ${_availableImplementations.map((impl) => impl.name).join(', ')}');

    if (!_availableImplementations.contains(implementationType)) {
      debugPrint('❌ 实现方案不在可用列表中');
      throw CameraError(
        code: 'IMPLEMENTATION_NOT_AVAILABLE',
        message: '指定的实现方案不可用',
      );
    }

    if (_currentImplementation == implementationType) {
      debugPrint('ℹ️ 已经是当前实现方案，无需切换');
      return; // 已经是当前实现方案
    }

    try {
      final oldImplementation = _currentImplementation;
      debugPrint('🔄 开始释放当前实现: ${oldImplementation?.name ?? 'null'}');

      // 释放当前实现
      await _disposeCurrentImplementation();
      debugPrint('✅ 当前实现已释放');

      debugPrint('🔄 开始初始化新实现: ${implementationType.name}');
      debugPrint('🔄 使用配置: ${_config != null ? 'config已设置' : 'config为null'}');

      // 初始化新实现
      await _initializeImplementation(implementationType);
      debugPrint('✅ 新实现初始化成功');

      // 更新状态以通知UI当前实现已改变
      _updateStatus(CameraStatus.initialized);
      debugPrint('📡 状态更新已触发');

      // 发送实现方案切换事件
      if (oldImplementation != null) {
        _eventController.add(CameraImplementationSwitchedEvent(
          oldImplementation,
          implementationType,
          '用户手动切换',
        ));
        debugPrint('📡 切换事件已发送');
      }

      // 保存用户偏好
      await _saveUserPreference(implementationType);
      debugPrint('💾 用户偏好已保存');
      debugPrint('🎉 实现方案切换完成');
    } catch (e, stackTrace) {
      debugPrint('❌ 切换实现方案失败: $e');
      debugPrint('📚 堆栈跟踪: $stackTrace');
      throw CameraError(
        code: 'SWITCH_IMPLEMENTATION_FAILED',
        message: '切换实现方案失败: ${e.toString()}',
      );
    }
  }

  /// 释放资源
  Future<void> dispose() async {
    debugPrint('🔄 MultiCameraManager: 开始释放资源...');

    _updateStatus(CameraStatus.disposed);

    // 释放当前实现
    await _disposeCurrentImplementation();

    // 重置状态
    _config = null;
    _currentImplementation = null;
    _autoInitializationEnabled = false;
    _isAutoInitializing = false;
    _isDetecting = false;
    _retryCount = 0;
    _availableImplementations.clear();

    // 关闭流控制器并重新创建，以支持重新初始化
    try {
      await _eventController.close();
      await _statusController.close();
      await _errorController.close();

      // 重新创建流控制器
      _eventController = StreamController<CameraEvent>.broadcast();
      _statusController = StreamController<CameraStatus>.broadcast();
      _errorController = StreamController<CameraError>.broadcast();
    } catch (e) {
      debugPrint('❌ 重新创建流控制器时发生错误: $e');
    }

    // 重置状态为未初始化
    _status = CameraStatus.uninitialized;

    debugPrint('✅ MultiCameraManager: 资源释放完成，可重新初始化');
  }

  // ========== 私有方法 ==========

  /// 更新状态
  void _updateStatus(CameraStatus status) {
    _status = status;
    _statusController.add(status);
    _eventController
        .add(CameraStatusChangedEvent(status, _currentImplementation));
  }

  /// 处理错误
  void _handleError(CameraError error) {
    _updateStatus(CameraStatus.error);
    _errorController.add(error);
    _eventController.add(CameraErrorEvent(error, _currentImplementation));
  }

  /// 处理预览错误并尝试自动降级
  void _handlePreviewError(CameraError error, Function(CameraError)? onError) {
    debugPrint('❌ MultiCameraManager: 预览错误，尝试智能错误处理: ${error.message}');

    // 使用智能错误处理
    if (_priority.enableSmartErrorHandling) {
      final severity = ErrorClassifier.classifyError(error.code, error.message);

      switch (severity) {
        case ErrorSeverity.severe:
          // 严重错误，直接处理，不降级
          debugPrint('❌ 预览严重错误，需要用户干预: ${error.message}');
          _handleError(error);
          onError?.call(error);
          return;

        case ErrorSeverity.minor:
          // 轻微错误，延迟后重试预览
          Future.microtask(() async {
            await Future.delayed(
                Duration(milliseconds: _priority.retryDelayMs));
            debugPrint('🔄 预览轻微错误，延迟后可能自动恢复');
            // 对于预览错误，我们不主动重试，而是让系统自然恢复
          });
          return;

        case ErrorSeverity.moderate:
          // 中等错误，尝试降级
          break;
      }
    }

    // 尝试自动降级
    if (_priority.enableAutoFallback && _retryCount < _priority.maxRetryCount) {
      Future.microtask(() async {
        try {
          await _tryFallbackImplementation('预览创建失败');
          debugPrint('✅ 预览错误降级成功');
        } catch (fallbackError) {
          debugPrint('❌ 预览错误降级也失败: $fallbackError');
          // 降级失败，正常处理错误
          _handleError(error);
          onError?.call(error);
        }
      });
    } else {
      // 不进行降级，正常处理错误
      _handleError(error);
      onError?.call(error);
    }
  }

  /// 检测可用的实现方案
  Future<void> _detectAvailableImplementations() async {
    if (_isDetecting) {
      debugPrint('🔍 MultiCameraManager: 正在检测中，跳过重复检测');
      return;
    }

    _isDetecting = true;
    debugPrint('🔍 MultiCameraManager: 开始检测可用实现方案');
    _availableImplementations.clear();

    // 检测Flutter Camera
    try {
      final flutterCameraAvailable =
          await FlutterCameraImplementation.isAvailable();
      debugPrint('🔍 Flutter Camera 可用性: $flutterCameraAvailable');
      if (flutterCameraAvailable) {
        _availableImplementations.add(CameraImplementationType.flutterCamera);
      }
    } catch (e) {
      debugPrint('❌ Flutter Camera 检测失败: $e');
    }

    // 检测原生实现
    try {
      final nativeAvailable = await NativeImplementation.isAvailable();
      debugPrint('🔍 Native 实现可用性: $nativeAvailable');
      if (nativeAvailable) {
        _availableImplementations.add(CameraImplementationType.native);
      }
    } catch (e) {
      debugPrint('❌ Native 实现检测失败: $e');
    }

    debugPrint(
        '🔍 最终可用实现: ${_availableImplementations.map((impl) => impl.name).join(', ')}');
    _isDetecting = false;
  }

  /// 选择最佳实现方案
  Future<CameraImplementationType?> _selectBestImplementation() async {
    // 首先尝试从用户偏好中获取
    final userPreference = await _getUserPreference();
    if (userPreference != null &&
        _availableImplementations.contains(userPreference)) {
      return userPreference;
    }

    // 根据平台和设备特性选择最佳方案
    if (Platform.isIOS) {
      // iOS平台优先级：原生 > Flutter Camera
      for (final impl in _priority.iosPriority) {
        if (_availableImplementations.contains(impl)) {
          return impl;
        }
      }
    } else if (Platform.isAndroid) {
      // Android平台优先级：Flutter Camera > 原生
      for (final impl in _priority.androidPriority) {
        if (_availableImplementations.contains(impl)) {
          return impl;
        }
      }
    }

    return _availableImplementations.isNotEmpty
        ? _availableImplementations.first
        : null;
  }

  /// 初始化指定的实现方案
  Future<void> _initializeImplementation(
      CameraImplementationType implementationType) async {
    if (_config == null) {
      throw CameraError(
        code: 'NO_CONFIG',
        message: '摄像头配置为空',
      );
    }

    switch (implementationType) {
      case CameraImplementationType.flutterCamera:
        await FlutterCameraImplementation.initialize(_config!);
        break;

      case CameraImplementationType.native:
        await NativeImplementation.initialize(_config!);
        break;
    }

    _currentImplementation = implementationType;
    _retryCount = 0; // 重置重试计数
  }

  /// 释放当前实现
  Future<void> _disposeCurrentImplementation() async {
    if (_currentImplementation == null) return;

    switch (_currentImplementation!) {
      case CameraImplementationType.flutterCamera:
        await FlutterCameraImplementation.dispose();
        break;

      case CameraImplementationType.native:
        await NativeImplementation.dispose();
        break;
    }

    _currentImplementation = null;
  }

  /// 保存用户偏好
  Future<void> _saveUserPreference(
      CameraImplementationType implementationType) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(
          'multi_camera_preferred_implementation', implementationType.name);
    } catch (e) {
      // 忽略保存偏好失败的错误
    }
  }

  /// 获取用户偏好
  Future<CameraImplementationType?> _getUserPreference() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final prefString =
          prefs.getString('multi_camera_preferred_implementation');
      if (prefString != null) {
        return CameraImplementationType.values.firstWhere(
          (e) => e.name == prefString,
          orElse: () => CameraImplementationType.flutterCamera,
        );
      }
    } catch (e) {
      // 忽略获取偏好失败的错误
    }
    return null;
  }

  /// 获取当前摄像头方向
  CameraLensDirection _getCurrentDirection() {
    switch (_currentImplementation) {
      case CameraImplementationType.flutterCamera:
        return FlutterCameraImplementation.currentDirection;
      case CameraImplementationType.native:
        return NativeImplementation.currentDirection;
      case null:
        return CameraLensDirection.back;
    }
  }

  /// 获取当前闪光灯模式
  FlashMode _getCurrentFlashMode() {
    switch (_currentImplementation) {
      case CameraImplementationType.flutterCamera:
        return FlutterCameraImplementation.currentFlashMode;
      case CameraImplementationType.native:
        return NativeImplementation.currentFlashMode;
      case null:
        return FlashMode.off;
    }
  }

  /// 尝试降级到其他实现方案
  Future<void> _tryFallbackImplementation(String reason) async {
    if (!_priority.enableAutoFallback ||
        _retryCount >= _priority.maxRetryCount) {
      return;
    }

    _retryCount++;

    // 获取当前平台的优先级列表
    final priorityList =
        Platform.isIOS ? _priority.iosPriority : _priority.androidPriority;

    // 找到当前实现在优先级列表中的位置
    int currentIndex = -1;
    if (_currentImplementation != null) {
      currentIndex = priorityList.indexOf(_currentImplementation!);
    }

    // 尝试下一个可用的实现方案
    for (int i = currentIndex + 1; i < priorityList.length; i++) {
      final nextImpl = priorityList[i];
      if (_availableImplementations.contains(nextImpl)) {
        try {
          final oldImplementation = _currentImplementation;

          // 释放当前实现
          await _disposeCurrentImplementation();

          // 初始化新实现
          await _initializeImplementation(nextImpl);

          // 发送自动切换事件
          if (oldImplementation != null) {
            _eventController.add(CameraImplementationSwitchedEvent(
              oldImplementation,
              nextImpl,
              '自动降级: $reason',
            ));
          }

          return;
        } catch (e) {
          // 如果这个实现也失败了，继续尝试下一个
          continue;
        }
      }
    }

    // 如果所有实现都失败了，抛出错误
    throw CameraError(
      code: 'ALL_IMPLEMENTATIONS_FAILED',
      message: '所有摄像头实现方案都失败了',
    );
  }

  /// 尝试在初始化阶段进行降级
  Future<void> _tryInitializationFallback(
      String reason, dynamic originalError) async {
    debugPrint('🔄 MultiCameraManager: 开始初始化降级，原因: $reason');

    // 获取当前平台的优先级列表
    final priorityList =
        Platform.isIOS ? _priority.iosPriority : _priority.androidPriority;

    // 找到当前尝试的实现在优先级列表中的位置
    int currentIndex = -1;
    if (_currentImplementation != null) {
      currentIndex = priorityList.indexOf(_currentImplementation!);
    }

    // 尝试下一个可用的实现方案
    for (int i = currentIndex + 1; i < priorityList.length; i++) {
      final nextImpl = priorityList[i];
      if (_availableImplementations.contains(nextImpl)) {
        try {
          debugPrint('🔄 尝试降级到: ${nextImpl.name}');
          final oldImplementation = _currentImplementation;

          // 释放当前实现（如果有的话）
          await _disposeCurrentImplementation();

          // 初始化新实现
          await _initializeImplementation(nextImpl);

          _updateStatus(CameraStatus.initialized);

          // 发送自动切换事件
          _eventController.add(CameraImplementationSwitchedEvent(
            oldImplementation ?? nextImpl, // 如果没有旧实现，使用当前实现
            nextImpl,
            '自动降级: $reason',
          ));

          // 保存用户偏好
          await _saveUserPreference(nextImpl);

          debugPrint('✅ 初始化降级成功: ${nextImpl.name}');
          return;
        } catch (e) {
          debugPrint('❌ 降级到 ${nextImpl.name} 失败: $e');
          // 如果这个实现也失败了，继续尝试下一个
          continue;
        }
      }
    }

    // 如果所有实现都失败了，抛出错误
    throw CameraError(
      code: 'ALL_IMPLEMENTATIONS_FAILED',
      message: '所有摄像头实现方案都失败了，原始错误: $originalError',
    );
  }
}
